import 'dart:async';

import 'package:chathouse/pages/expert/buyWallet/recharge_bank_card.dart';
import 'package:chathouse/util/base_utils.dart';
import 'package:chathouse/web_socket/web_socket_channel.dart';
import 'package:flutter/material.dart';
import 'package:chathouse/public/Config.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../chat/chat_page.dart';
import '../../constant/app_constant.dart';
import '../../model/expert_message.dart';
import '../../model/member_info.dart';
import '../../public/empty_widget.dart';
import '../../util/log.dart';
import '../base/base.dart';

///专家对话记录
class MessageListPage extends BaseStatefulWidget {
  const MessageListPage({Key? key}) : super(key: key);

  @override
  _MessageListPageState createState() => _MessageListPageState();
}

class _MessageListPageState extends BaseStatefulWidgetState<MessageListPage>
    with AutomaticKeepAliveClientMixin {
  MyWebSocketChannel socket = MyWebSocketChannel.instance;

  ExpertMessage? messages;
  final RefreshController _refreshController =
      RefreshController(initialRefresh: false); // 刷新控件控制

  int pageNum = 1;
  List<Rows>? rows = [];

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    updateEmptyPage(tipTitle: "暫無会话信息數據");
    updateState(LoadState.empty);
    setState(() {
      scaffoldBackColor = Colors.white;
    });
    loadMessage();
  }

  loadMore() {
    pageNum += 1;
    loadMessage();
  }

  clearLoad() {
    pageNum = 1;
    rows?.clear();
    loadMessage();
  }

  void loadMessage() {
    Object? json = SpUtil.getObject2(AppConstant.memberInfo);
    var memberInfo;
    if (json != null) {
      memberInfo = MemberInfo.fromJson2(json);
      LogUtil.d("當前用戶的編號： ${memberInfo.data?.membersNo.toString() ?? ""}");
    }
    final params = {
      "kind": "1",
      "pageNum": pageNum,
      "membersNo": memberInfo.data?.membersNo.toString() ?? "",
    };
    Obj.showLoading();
    Apis.getSessionList(params)
        .then((response) => {
              _refreshController.refreshCompleted(),
              _refreshController.loadComplete(),
              Obj.dismissLoading(),
              setState(() {
                messages = ExpertMessage.fromJson(response?.data);
                rows?.addAll(messages?.rows ?? []);
              })
            })
        .onError((error, stackTrace) => {
              _refreshController.refreshCompleted(),
              _refreshController.loadComplete(),
              Obj.dismissLoading()
            });
  }

  Widget item(idx) {
    Rows item = rows![idx];
    return Container(
      padding: EdgeInsets.symmetric(vertical: Styles.magin_16),
      width: double.infinity,
      child: InkWell(
        onTap: () {
          final map = {
            "reviceuserId": item.adverseNo,
            "projectNo": item.projectNo,
            "memberImage": item.memberImage,
            "membersName": item.adverseName,
            "projectId": item.projectId,
            "id": item.id,
            "projectLabel": item.projectLabel
          };
          Get.to(ChatPage(map));
        },
        child: Row(
          children: [
            (item?.memberImage ?? "").isNotEmpty ? ImageUtils.image(item?.memberImage ?? "",
                width: 55.w,
                height: 55.w,
                imageType: ImageType.NETWORK,
                radius: 30.w)
                .setContainer(margin: EdgeInsets.only(right: Styles.magin_12))
                : ImageUtils.image('assets/images/expert_avatar.png',
                width: 55.w,
                height: 55.w,
                imageType: ImageType.ASSET,
                radius: 30.w)
                .setContainer(margin: EdgeInsets.only(right: Styles.magin_12)),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    width: double.infinity,
                    child: Stack(
                      children: [
                        Text(item.adverseName ?? "",
                            style: getTextStyle(
                              22.w,
                              fontType: FontType.BOLD,
                              color: Styles.c_333,
                            )),
                        Positioned(
                          top: 0,
                          right: 0,
                          child: Text(item.updateTime ?? "",
                              style: getTextStyle(
                                14.w,
                                color: Styles.c_999,
                              )),
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(
                    height: 6,
                  ),
                  Container(
                    width: double.infinity,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(item.projectName ?? '',
                            style: getTextStyle(
                              16.w,
                              fontType: FontType.BOLD,
                              color: Styles.c_333,
                            )),
                        Container(
                          margin: EdgeInsets.only(right: 2.w),
                          child: item.neverRead != 0
                              ? Container(
                                  width: 8,
                                  height: 8,
                                  decoration: BoxDecoration(
                                      color: Colors.redAccent,
                                      borderRadius: BorderRadius.circular(4)),
                                )
                              : Container(),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return rows?.length == 0
        ? const Align(
            child: EmptyWidget(
              emptyText: '暂無通知數據',
            ),
            alignment: Alignment.center,
          )
        : SmartRefresher(
            enablePullDown: true,
            enablePullUp: true,
            controller: _refreshController,
            onRefresh: clearLoad,
            onLoading: () {
              loadMore();
            },
            child: ListView.separated(
                itemBuilder: (context, index) {
                  return item(index);
                },
                separatorBuilder: (context, index) {
                  return Container(
                    height: 0.6,
                    color: Styles.cf3,
                  );
                },
                itemCount: rows?.length ?? 0),
          );
  }
}
